<?php
/**
 * CRM_Controller - базовый контроллер системы
 * 
 * @author Mazvv
 * @abstract
 * @package Extenders
 */
abstract class CRM_Controller extends Controller 
{
	private $a_User = null;
	private $a_objectsList = array();
	protected $a_identifier;
	private $a_newToolSize = '700x700';
	private $a_editToolSize = '700x700';
	private $a_detailsToolSize = '700x700';
	private $a_findToolSize = '700x700';
	private $a_perPage = '20';
	private $a_pagination;
	private $a_fieldsList = array();
	public $a_validation_rules;
	public $a_validation_fields;
	
	public function __construct() {
		parent::Controller();
		$this->output->enable_profiler(False);
		$this->lang->load('tools');
		$this->lang->load('common');
		$this->load->library('user');
		$currentUriString = $this->uri->uri_string();
		if($this->CheckAuthStatus()){
			require_once(APPPATH.'libraries/CRM_Model.php');
			require_once(APPPATH.'libraries/Presentation/Excel/Writer.php');
			require_once(APPPATH.'libraries/Presentation/PDF/Fpdf.php');
			$this->CreateUser();
		}
		else if(!empty($currentUriString) && $currentUriString!=='/login/l') redirect('', 'refresh');
	}
	
	/**
	 * Проверка авторизирован ли уже пользователь
	 * 
	 * @author Mazvv
	 * @param void
	 * @access private
	 * @return boolean
	 */
	private function CheckAuthStatus()	{
		$auth = $this->session->userdata('AUTH');
		if(!$auth) return False;
		return True;
	}
	
	/**
	 * Создание объекта пользователя
	 * 
	 * @author Mazvv
	 * @param void
	 * @return void
	 */
	private function CreateUser(){
		$this->user->InitUser();
		return;
	}
	
	protected function SetDefaultView($p_defaultView){
		$this->a_defaultView = $p_defaultView; 
	}
	
	public function SetSessionData($p_name, $p_value){
		$sessionData = $this->session->userdata($this->a_identifier);
		$sessionData[$p_name] = $p_value; 
		$this->session->set_userdata($this->a_identifier, $sessionData);
	}
	
	public function GetSessionData($p_name){
		$sessionData = $this->session->userdata($this->a_identifier);
		return isset($sessionData[$p_name])?$sessionData[$p_name]:null;
	}
	
	public function RefreshSessionData(){
		$this->session->set_userdata($this->a_identifier, null);		
	}
	
	public function GetIdentifier(){
		return $this->a_identifier;
	}
	
	public function GetNewTool(){
		$sizeArr = explode('x', $this->a_newToolSize);
		$content['width'] = $sizeArr[0];
		$content['height'] = $sizeArr[1];
		$content['identifier'] = $this->GetIdentifier();
		return $this->load->view('standart/tools/new', $content, True);
	}
	
	public function GetDetailsTool(){
		$sizeArr = explode('x', $this->a_detailsToolSize);
		$content['width'] = $sizeArr[0];
		$content['height'] = $sizeArr[1];
		$content['identifier'] = $this->GetIdentifier();
		return $this->load->view('standart/tools/details', $content, True);
	}

	public function GetEditTool(){
		$sizeArr = explode('x', $this->a_editToolSize);
		$content['width'] = $sizeArr[0];
		$content['height'] = $sizeArr[1];
		$content['identifier'] = $this->GetIdentifier();
		return $this->load->view('standart/tools/edit', $content, True);
	}

	public function GetRemoveTool(){
		$content['identifier'] = $this->GetIdentifier();
		return $this->load->view('standart/tools/remove', $content, True);
	}
	
	public function GetRefreshTool(){
		$content['identifier'] = $this->GetIdentifier();
		return $this->load->view('standart/tools/refresh', $content, True);
	}

	public function GetFindTool(){
		$sizeArr = explode('x', $this->a_findToolSize);
		$content['width'] = $sizeArr[0];
		$content['height'] = $sizeArr[1];
		$content['identifier'] = $this->GetIdentifier();
		return $this->load->view('standart/tools/find', $content, True);
	}
	
	public function GetFilterTool(){
		$content['identifier'] = $this->GetIdentifier();
		//return $this->load->view('standart/tools/filter', $content, True);
		return '';
	}
	
	public function GetTools(){
		$tools = array();
		$tools['filter'] = $this->GetFilterTool();
		$tools['find'] = $this->GetFindTool();
		$userRightsArr = explode('|', $this->menucontainer->GetItemRights());
		foreach($userRightsArr as $item){
			switch ($item){
				case 'N':{$tools['new']=$this->GetNewTool();break;}
				case 'E':{$tools['edit']=$this->GetEditTool();break;}
				case 'D':{$tools['details']=$this->GetDetailsTool();break;}
				case 'R':{$tools['remove']=$this->GetRemoveTool();break;}
			}
		}
		$tools['refresh'] = $this->GetRefreshTool();
		return $tools;
	}

	
	public function SetNewToolSize($p_size){
		$this->a_newToolSize = $p_size;
	}
	
	public function SetEditToolSize($p_size){
		$this->a_editToolSize = $p_size;
	}

	public function SetDetailsToolSize($p_size){
		$this->a_detailsToolSize = $p_size;
	}
	
	public function SetFindToolSize($p_size){
		$this->a_findToolSize = $p_size;
	}
	
	public function RenderPagination($p_totalRows){
		$this->load->library('pagination');
		$config['base_url'] = site_url().'/'.$this->uri->segment(1).'/pg/';
		$config['total_rows'] = $p_totalRows;
		$config['uri_segment'] = 3;
		$config['num_links'] = 5;
		$config['per_page'] = $this->GetPerPage();
		$this->pagination->initialize($config);
		$this->a_pagination = $this->pagination->create_links();
	}
	
	public function GetPagination(){
		return $this->a_pagination;
	}
	
	public function GetPerPage(){
		return $this->a_perPage;	
	}

	public function SetPerPage($p_perPage){
		$this->a_perPage = $p_perPage;	
	}

	public function GetPagingDS($p_ds){
		$this->RenderPagination(count($p_ds));
		if($this->uri->segment(2)=='pg' && $ofset = $this->uri->segment(3)){
			return array_slice($p_ds, $ofset, $this->GetPerPage());	
		}	
		return array_slice($p_ds, 0, $this->GetPerPage());
	}

	public function IsRequired($p_fieldName){
		if(isset($this->a_validation_rules[$p_fieldName]))
			return (array_search('required', explode('|',$this->a_validation_rules[$p_fieldName]))===False)?False:True;
		return False;
	}
	
	public function RenderLabel($p_fieldName){
		return $this->a_validation_fields[$p_fieldName].($this->IsRequired($p_fieldName)?'&nbsp;<font color="red">*</font>':'');
	}
	
	
	public function RenderCalendar($p_fieldID){
		return "<button class=\"button\" type=\"reset\" id=\"{$p_fieldID}_b\">...</button>
				<script type=\"text/javascript\">
    				Calendar.setup({
        				inputField     :    \"{$p_fieldID}\",
        				ifFormat       :    \"%d.%m.%Y\",
        				showsTime      :    false,
				        button         :    \"{$p_fieldID}_b\",   
        				singleClick    :    true,           
        				step           :    1               
    				});
				</script>
				";
	}
	
	/* { SERVICE */
	public function _sort(){
		$p_column = $this->uri->segment(3);
		$sort = array('c'=>$p_column, 'r'=>'ASC');
		if($oldSort = $this->GetSessionData('sort')){
			if($oldSort['c']==$p_column) {
				$sort['r'] = ($oldSort['r']=='ASC')?'DESC':'ASC';
			}
		}
		$this->SetSessionData('sort', $sort);
		echo $this->_journal();
	}
	
	public function _activerecord(){
		$this->SetSessionData('activerecord', $this->uri->segment(3));
		echo $this->_journal();
	}

	public function _setactiverecord(){
		$this->SetSessionData('activerecord', $this->uri->segment(3));
	}
	
	public function _setsearchrule($p_searchrule){
		$this->SetSessionData('searchrule', $p_searchrule);
	}
	/* } SERVICE */
	
}
?>